package com.psy.counseling.service.impl;

import cn.dev33.satoken.stp.StpUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.psy.counseling.entity.Role;
import com.psy.counseling.entity.RolePermission;
import com.psy.counseling.entity.UserRole;
import com.psy.counseling.mapper.RoleMapper;
import com.psy.counseling.mapper.RolePermissionMapper;
import com.psy.counseling.mapper.UserRoleMapper;
import com.psy.counseling.service.RoleService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.psy.counseling.vo.DeleteVO;
import com.psy.counseling.vo.PageVO;
import com.psy.counseling.vo.ResultVo;
import com.psy.counseling.vo.RolePermissionVo;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

import java.util.stream.Collectors;

import static org.apache.ibatis.ognl.OgnlOps.longValue;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author 梁学儒
 * @since 2022-05-31
 */
@Service("roleService")
public class RoleServiceImpl extends ServiceImpl<RoleMapper, Role> implements RoleService {
    @Resource
    private RoleMapper roleMapper;

    @Resource
    private UserRoleMapper userRoleMapper;

    @Resource
    private RolePermissionMapper rolePermissionMapper;

    public List<String> getRoleListById() {
        QueryWrapper<UserRole> userRoleQW = new QueryWrapper<>();
        int userId = StpUtil.getLoginIdAsInt();
        userRoleQW.eq("id", userId);
        List<UserRole> userRoles = userRoleMapper.selectList(userRoleQW);
        List<Role> roles = new ArrayList<>();
        for(UserRole userRole : userRoles){
            Long roleId  = userRole.getRolId();
            QueryWrapper<Role> wrapper = new QueryWrapper<>();
            wrapper.eq("id", roleId);
            Role role = roleMapper.selectOne(wrapper);
            roles.add(role);
        }
        return roles.stream().map(Role::getRoleName).collect(Collectors.toList());
    }

    /**
     * 添加角色
     * @param role
     * @return ResultVo
     */
    @Transactional
    public ResultVo addRole(Role role){
        if(ObjectUtils.isEmpty(role)){
            return ResultVo.builder().code("400").msg("添加失败!").data("角色不能为空").build();
        }else {
            LambdaQueryWrapper<Role> RQW = new LambdaQueryWrapper<>();
            RQW.eq(Role::getRoleName,role.getRoleName());
            int i = this.count(RQW);
            if (i>0){
                return ResultVo.builder().code("400").msg("添加失败!").data("角色名已经被使用").build();
            }
            if(roleMapper.insert(role)>=1){
                return ResultVo.builder().code("200").msg("添加成功!").data(role).build();
            }
            else {
                return ResultVo.builder().code("500").msg("添加失败!").data("系统错误").build();
            }
        }
    }

    /**
     * 删除角色
     * @param deleteVO
     * @return ResultVo
     */
    @Transactional
    public ResultVo deleteRole(DeleteVO deleteVO){
        if(ObjectUtils.isNotEmpty(deleteVO.getId())){
            if(this.removeById(deleteVO.getId())){
                return ResultVo.builder().code("200").msg("删除成功!").data(null).build();
            }
        }else if(ObjectUtils.isNotEmpty(deleteVO.getIds())){
            if(this.removeByIds(deleteVO.getIds())){
                return ResultVo.builder().code("200").msg("删除成功!").data(null).build();
            }
        }else {
            return ResultVo.builder().code("400").msg("删除失败!").data("id不能为空").build();
        }
        return ResultVo.builder().code("500").msg("删除失败!").data("系统错误").build();
    }

    /**
     * 查询角色
     * @param role
     * @param page
     * @return ResultVo
     */
    @Transactional
    public ResultVo listRoles(Role role, PageVO page) {
        Page<Role> firstVisitPage = new Page<>(page.getPageNum(),page.getPageSize());
        LambdaQueryWrapper<Role> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(ObjectUtils.isNotEmpty(role.getId()),Role::getId,role.getId())
                .eq(ObjectUtils.isNotEmpty(role.getRoleName()),Role::getRoleName,role.getRoleName());
        firstVisitPage = this.page(firstVisitPage,queryWrapper);
        return ResultVo.builder().code("200").msg("查询成功!").data(firstVisitPage).build();
    }

    /**
     * 修改角色
     * @param role
     * @return ResultVo
     */
    @Transactional
    public ResultVo updateRole(Role role){
        if(ObjectUtils.isNotEmpty(role.getId())){
            QueryWrapper<Role> wrapper = new QueryWrapper<>();
            wrapper.eq("id",role.getId());
            Role role1 = roleMapper.selectById(role.getId());
            LambdaQueryWrapper<Role> RQW = new LambdaQueryWrapper<>();
            RQW.eq(Role::getRoleName,role.getRoleName());
            int i = this.count(RQW);
            if (i>0){
                return ResultVo.builder().code("400").msg("修改失败!").data("此角色已经被占用").build();
            }
            role1.setRoleName(role.getRoleName());
            roleMapper.update(role1,wrapper);
            return ResultVo.builder().code("200").msg("修改成功!").data(role1).build();
        }else {
            return ResultVo.builder().code("400").msg("修改失败!").data("角色id不能为空").build();
        }
    }

    /**
     * 设置角色权限
     * @param rolePermissionVo
     * @return ResultVo
     */
    @Transactional
    public ResultVo updateRolePermission(RolePermissionVo rolePermissionVo){
        if(ObjectUtils.isNotEmpty(rolePermissionVo.getRoleId())&&ObjectUtils.isNotEmpty(rolePermissionVo.getPermissionIds())){
            QueryWrapper<RolePermission> wrapper = new QueryWrapper<>();
            wrapper.eq("id",rolePermissionVo.getRoleId());
            rolePermissionMapper.delete(wrapper);
            RolePermission rolePermission = new RolePermission();
            rolePermission.setId(rolePermissionVo.getRoleId());
            for(Long list : rolePermissionVo.getPermissionIds()){
                rolePermission.setPerId(list);
                rolePermissionMapper.insert(rolePermission);
            }
            return ResultVo.builder().code("200").msg("修改成功!").data(rolePermissionVo).build();
        }else {
            return ResultVo.builder().code("400").msg("修改失败!").data("id不能为空").build();
        }
    }

}
